package com.yl.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加密
 * @author : y
 * @date :  2024/6/24 10:23
 **/
public class RSACrypot {
    public static PublicKey getPublicKey(String publicKeyString) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }
    public static String encryptWithPublicKey(String text, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    public static void main(String[] args) throws Exception {
        String publicKeyString = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA82hi5YgKzh9JH1oa5qWz" +
                "lkghF/r8UBH8uMBCG9rIBG1eTNqXd4Bw6B2cOhH54UJ4lrCrh01aDvymNz43/mrG" +
                "ZM/22CaT9ITsD5QK84PNJrS3sxxN6ZVH+FI3e8xplzsz3aDxbb2i5xqcijo6ze/v" +
                "E7W1GOEy6jh2TuAlufz/WOLcI9KwWAVnj+SA3/7BYDW4S2LfSlLwo0JwBUZzENZo" +
                "2K2a4pJzpkqNLQxcXeoAHmDZC7n9Q/KZMP8FZuNIzffE9k/EtuYjDe40pjtl/b8m" +
                "ZalM5sgnfrPiS1YZXlm5nlf6IFAT/pM7GBBlNJ3FRwyXuyM4/9xKF0dqv+lvZ0YS" +
                "0QIDAQAB";
        PublicKey publicKey = getPublicKey(publicKeyString);

        String textToEncrypt = "Hello, World!";
        String encryptedText = encryptWithPublicKey(textToEncrypt, publicKey);

        System.out.println("Encrypted Text: " + encryptedText);
    }


    // public static String rsaEncode(String plainText) throws Exception {
    //     byte[] msg = plainText.getBytes();
    //     PublicKey pubKey = getPublicKey(PUBLIC_KEY);
    //     Cipher cipher = Cipher.getInstance("RSA");
    //     cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    //     byte[] encryptText = cipher.doFinal(msg);
    //     return Base64.getEncoder().encodeToString(encryptText);
    // }


}
